<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt" %> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title><fmt:message key="main.title"/></title>
    <meta content="text/html; charset=utf-8" http-equiv="content-type" />
    <link rel="stylesheet" type="text/css" href="/extjs/css/ext-all.css" />
    <link rel="stylesheet" type="text/css" href="/extjs/icons/silk.css" />
    <link rel="stylesheet" type="text/css" href="/css/main.css" />
    <style type="text/css">
        #loading-mask {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color:white;
            z-index: 20000;
        }
        #loading {
            height:auto;
            position: absolute;
            top: 40%;
            left: 45%;
            padding:2px;
            z-index:20001;
        }
        #loading .loading-indicator{
            background:white;
            color:#444;
            font:bold 13px Helvetica, Arial, sans-serif;
            height:auto;
            margin:0;
            padding:10px;
        }
        #loading-msg {
            font-size: 10px;
            font-weight: normal;
        }
    </style>
    <!--  filters -->
    <link rel="stylesheet" type="text/css" href="/extjs/examples/ux/gridfilters/css/GridFilters.css" />
    <link rel="stylesheet" type="text/css" href="/extjs/examples/ux/gridfilters/css/RangeMenu.css" />

</head>
<body>
     <div id="loading-mask"></div>
     <div id="loading">
          <div class="loading-indicator"><img src="/images/loading.gif" width="32" height="32" style="margin-right:8px;float:left;vertical-align:top;"/><br/><span id="loading-msg"><fmt:message key="message.loading"/>...</span></div>
     </div>
    <script type="text/javascript" src="/extjs/adapter/ext/ext-base.js"></script>
    <script type="text/javascript" src="/extjs/ext-all.js"></script>
    <script type="text/javascript" src="/extjs/locale/ext-lang-<%= System.getProperty("user.language") %>.js"></script>
    <!-- extensions -->

    <script type="text/javascript" src="/extjs/examples/ux/gridfilters/menu/RangeMenu.js"></script>
    <script type="text/javascript" src="/extjs/examples/ux/gridfilters/menu/ListMenu.js"></script>
    <script type="text/javascript" src="/extjs/examples/ux/gridfilters/GridFilters.js"></script>
    <script type="text/javascript" src="/extjs/examples/ux/gridfilters/filter/Filter.js"></script>
    <script type="text/javascript" src="/extjs/examples/ux/gridfilters/filter/StringFilter.js"></script>
    <script type="text/javascript" src="/extjs/examples/ux/gridfilters/filter/DateFilter.js"></script>
    <script type="text/javascript" src="/extjs/examples/ux/gridfilters/filter/ListFilter.js"></script>
    <script type="text/javascript" src="/extjs/examples/ux/gridfilters/filter/NumericFilter.js"></script>
    <script type="text/javascript" src="/extjs/examples/ux/gridfilters/filter/BooleanFilter.js"></script>

    <script type="text/javascript" src="/ckeditor/ckeditor.js"></script>
    <script type="text/javascript">
    function yesnoRenderer (val) {
        var html = '<div unselectable="on" class="x-grid3-cell-inner x-grid3-col-2">';
        if (val) {
            html += '<fmt:message key="label.yes"/>';
        } else {
            html += '<fmt:message key="label.no"/>';
        }
        html += '</div>';
        return html;
    }
    </script>
    <script type="text/javascript">
    Ext.onReady(function(){
        Ext.QuickTips.init();
        Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
        Ext.data.JsonHttpProxy = function(config) {
            return new Ext.data.HttpProxy(Ext.apply({
                headers:{'Accept':'application/json'}
            }, config));
        };

        Ext.ns('ru.minidoc');
        (function(){
            var Context = Ext.extend(Object,{
                viewport: undefined,
                editor: undefined,
                historyDataStore: undefined,

                constructor: function(config){
                    Ext.apply(this, config)
                },

                getDocumentId: function() {
                    return document.getElementById("documentId").value;
                },
                setDocumentId: function(documentId) {
                    document.getElementById("documentId").value = documentId;
                },
                getEditorPanel: function() {
                    return viewport.items.get(2).get(0).get(1).get(0);
                },
                documentSaveText: function (editor) {
                    if (this.getDocumentId() >=0) {
                        Ext.MessageBox.show({
                            msg: '<fmt:message key="message.saving"/>',
                            progressText: '<fmt:message key="label.saving"/>',
                            width:300,
                            wait:true,
                            waitConfig: {interval:200},
                            icon:'ext-mb-download', //custom class in msg-box.html
                            animEl: 'mb7'
                        });

                        //ajax save
                        Ext.Ajax.request({
                            url: '/document/save.action',
                            success: function(response) {
                                documentContext.editor.resetDirty();
                                documentContext.historyDataStore.load();
                                Ext.MessageBox.hide();
                            },
                            failure: function () {
                                Ext.MessageBox.hide();
                                Ext.MessageBox.alert('<fmt:message key="label.attention"/>', '<fmt:message key="label.ajaxerror"/>'); 
                            },
                            method: 'POST',
                            jsonData: {'id': documentContext.getDocumentId(), 'text': documentContext.editor.getData()}
                        });
                    }
                }
                
            })

            ru.minidoc.Context = Context;
        })()

        var documentDataStore = new Ext.data.GroupingStore({
            id: 'document',
            pruneModifiedRecords: true,
            proxy: Ext.data.JsonHttpProxy({
                api: {
                    read :    '/document/read.action',
                    create :  '/document/create.action',  // Server MUST return idProperty of new record
                    update :  '/document/update.action',
                    destroy : '/document/destroy.action'
                }
            }),
            reader: new Ext.data.JsonReader({
                root: 'rows',
                fields: [
                         {name: 'id' },
                         {name: 'name'},
                         {name: 'assignedTo'},
                         {name: 'modified'},
                         {name: 'modifiedBy'},
                         {name: 'version'},
                         {name: 'project'}
                ]
            }),
            writer: new Ext.data.JsonWriter({
                encode: false,
                writeAllFields: true
            }),
            sortInfo:{field: 'name', direction: "ASC"},
            groupField:'project'
        });

        var documentGridFilters = new Ext.ux.grid.GridFilters({
            encode: false,
            local: true,
            menuFilterText : '<fmt:message key="label.filters"/>',
            filters: [{
                type: 'string',
                dataIndex: 'project'
            }, {
                type: 'string',
                dataIndex: 'name'
            }]
        });    
        
        var documentGrid = new Ext.grid.GridPanel({
            store: documentDataStore,
            title: '<fmt:message key="title.documents"/>',
            columns: [
                {id:'document',header: '<fmt:message key="document.grid.name"/>', width: 50, sortable: true, dataIndex: 'name', filterable:true, filter: {type: 'string'}},
                {header: '<fmt:message key="document.grid.assignedTo"/>', width: 50, sortable: true, dataIndex: 'assignedTo'},
                {header: '<fmt:message key="document.grid.modifiedBy"/>', width: 40, sortable: true, dataIndex: 'modifiedBy'},
                {header: '<fmt:message key="document.grid.modified"/>', width: 40, sortable: true, dataIndex: 'modified'},
                {header: '<fmt:message key="document.grid.project"/>', width: 40, sortable: true, visible: false, dataIndex: 'project', hidden: true}
            ],
    
            view: new Ext.grid.GroupingView({
                forceFit:true,
                groupTextTpl: '{text} ({[values.rs.length]} {[values.rs.length > 1 ? "<fmt:message key="document.grid.items"/>" : "<fmt:message key="document.grid.items"/>"]})'
            }),
            plugins: [documentGridFilters],
            frame: true,
            height: 500,
            iconCls: 'icon-grid',
            listeners: {
                rowclick:function(grid, rowIndex, e) {
                    
                    var selectedRow = grid.getSelectionModel().getSelected();
                    if (documentEditor.checkDirty()) {
                        Ext.MessageBox.confirm('<fmt:message key="label.confirm"/>', '<fmt:message key="message.textchanged"/>', function(selected) {
                            if (selected != "yes") {
                                return false;
                            }
                            documentEditor.execCommand('save');;
                        });
                    }
                    Ext.MessageBox.show({
                        msg: '<fmt:message key="message.loading"/>',
                        progressText: '<fmt:message key="label.loading"/>',
                        width:300,
                        wait:true,
                        waitConfig: {interval:200},
                        icon:'ext-mb-download', //custom class in msg-box.html
                        animEl: 'mb7'
                    });
                    //selectedRow.id;
                    //ajax loading text
                    Ext.Ajax.request({
                        url: '/document/load.action',
                        success: function(response) {
                            var json = Ext.decode( response.responseText );
                            documentEditor.setData(json.text);
                            documentEditor.resetDirty(json.id);
                            documentContext.setDocumentId(json.id);
                            Ext.apply(documentHistoryDataStore.baseParams, {'id': documentContext.getDocumentId()}); 
                            documentHistoryDataStore.load();
                            Ext.MessageBox.hide();
                        },
                        failure: function () {
                            Ext.MessageBox.hide();
                            Ext.MessageBox.alert('<fmt:message key="label.attention"/>', '<fmt:message key="label.ajaxerror"/>'); 
                        },
                        method: 'POST',
                        jsonData: {'id': selectedRow.id}
                    });
                }
            }
        });
    
        var documentHistoryDataStore = new Ext.data.Store({
            id: 'documentHistory',
            proxy: Ext.data.JsonHttpProxy({
                api: {
                    read : {url: '/document/history/read.action', method: 'GET'}
                }
            
            }),
            reader: new Ext.data.JsonReader({
                root: 'rows',
                fields: [
                         {name: 'id' },
                         {name: 'name'},
                         {name: 'assignedTo'},
                         {name: 'modified'},
                         {name: 'modifiedBy'},
                         {name: 'version'},
                         {name: 'documentId'},
                         {name: 'project'}
                ]
            }),
            sortInfo:{field: 'version', direction: "DESC"}
        });

        var documentHistoryGrid = new Ext.grid.GridPanel({
            store: documentHistoryDataStore,
            title: '<fmt:message key="title.documents"/>',
            columns: [
                {id:'document',header: '<fmt:message key="document.grid.name"/>', width: 150, sortable: true, dataIndex: 'name'},
                {header: '<fmt:message key="document.grid.modifiedBy"/>', width: 140, sortable: true, dataIndex: 'modifiedBy'},
                {header: '<fmt:message key="document.grid.modified"/>', width: 140, sortable: true, dataIndex: 'modified'},
                {header: '<fmt:message key="document.grid.version"/>', width: 140, sortable: true, visible: false, dataIndex: 'version'}
            ],
            frame: true,
            height: 500,
            iconCls: 'icon-grid',
            listeners: {
                rowclick:function(grid, rowIndex, e) {
                    var selectedRow = grid.getSelectionModel().getSelected();
                    Ext.MessageBox.confirm('<fmt:message key="label.confirm"/>', '<fmt:message key="message.loadversion"/>', function(selected) {
                        if (selected != "yes") {
                            return;
                        }
                        Ext.MessageBox.show({
                            msg: '<fmt:message key="message.loading"/>',
                            progressText: '<fmt:message key="label.loading"/>',
                            width:300,
                            wait:true,
                            waitConfig: {interval:200},
                            icon:'ext-mb-download', //custom class in msg-box.html
                            animEl: 'mb7'
                        });
                        //selectedRow.id;
                        //ajax loading text
                        Ext.Ajax.request({
                            url: '/document/history/load.action',
                            success: function(response) {
                                var json = Ext.decode( response.responseText );
                                documentContext.editor.setData(json.text);
                                documentContext.editor.resetDirty();
                                documentContext.setDocumentId(json.id);
                                documentContext.getEditorPanel().activate(0);
                                Ext.MessageBox.hide();
                            },
                            failure: function () {
                                Ext.MessageBox.hide();
                                Ext.MessageBox.alert('<fmt:message key="label.attention"/>', '<fmt:message key="label.ajaxerror"/>'); 
                            },
                            method: 'POST',
                            jsonData: {'id': selectedRow.data.documentId, 'version': selectedRow.data.version}
                        });
                    });
                }
            }
        });
<c:if test="${managerMode}">
        var userListDataStore = new Ext.data.JsonStore({
            // store config
            //autoDestroy: true,
            url: '/user/read.action',
            storeId: 'userListStore',
            // reader configs
            root: 'rows',
            idProperty: 'id',
            fields: ['id', 'fullname']
        });

        var projectListDataStore = new Ext.data.JsonStore({
            // store config
            //autoDestroy: true,
            url: '/project/read.action',
            storeId: 'projectListStore',
            // reader configs
            root: 'rows',
            idProperty: 'id',
            fields: ['id', 'name']
        });

        var documentListDataStore = new Ext.data.GroupingStore({
            id: 'documentList',
            pruneModifiedRecords: true,
            proxy: Ext.data.JsonHttpProxy({
                api: {
                    read :    '/documentList/read.action',
                    create :  '/documentList/create.action',  // Server MUST return idProperty of new record
                    update :  '/documentList/update.action',
                    destroy : '/documentList/destroy.action'
                }
            }),
            reader: new Ext.data.JsonReader({
                root: 'rows',
                fields: [
                         { name: 'id' },
                         { name: 'name' },
                         { name: 'assignedToId' },
                         { name: 'assignedTo' },
                         { name: 'modified' },
                         { name: 'project' },
                         { name: 'projectId' }
                ]
            }),
            writer: new Ext.data.JsonWriter({
                encode: false,
                writeAllFields: true
            })
        });

        var documentListGrid = new Ext.grid.GridPanel({
            iconCls: 'icon-grid',
            frame: true,
            title: '<fmt:message key="title.documents"/>',
            store: documentListDataStore,
            columns: [
                {id:'id',header: '<fmt:message key="documentList.grid.name"/>', width: 150, sortable: true, dataIndex: 'name'},
                {header: '<fmt:message key="documentList.grid.project"/>', width: 150, sortable: true, dataIndex: 'project'},
                {header: '<fmt:message key="documentList.grid.assignedTo"/>', width: 150, sortable: true, dataIndex: 'assignedTo'},
                {header: '<fmt:message key="documentList.grid.modified"/>', width: 140, sortable: true, dataIndex: 'modified'}
            ],
            view: new Ext.grid.GroupingView({
                forceFit:true
            }),
            tbar: [{
                text: '<fmt:message key="documentList.add"/>',
                iconCls: 'silk-add',
                handler : function(){
                    documentListEditForm.getForm().reset();
                    userListDataStore.load();
                    projectListDataStore.load();
                    documentListEditWindow.createOnSave = true;
                    documentListEditWindow.show();
                }
            }, {
                text: '<fmt:message key="documentList.edit"/>',
                handler : function(){
                    var selectedRow = documentListGrid.getSelectionModel().getSelected();
                    if (!selectedRow) {
                        Ext.MessageBox.alert('<fmt:message key="label.attention"/>', '<fmt:message key="label.nothingselected"/>');
                        return false;
                    }
                    var rec = documentListGrid.store.getById(selectedRow.id);
                    documentListEditForm.getForm().loadRecord(rec);
                    documentListEditWindow.createOnSave = false;
                    documentListEditWindow.recordToEdit = rec;
                    documentListEditWindow.show();
                    documentListGrid.stopEditing();
                }
            }, {
                text: '<fmt:message key="documentList.delete"/>',
                iconCls: 'silk-delete',
                handler : function() {
                    var selectedRow = documentListGrid.getSelectionModel().getSelected();
                    if (!selectedRow) {
                        Ext.MessageBox.alert('<fmt:message key="label.attention"/>', '<fmt:message key="label.nothingselected"/>');
                        return false;
                    }
                    Ext.MessageBox.confirm('<fmt:message key="label.confirm"/>', '<fmt:message key="label.areyousure"/>', function(selected) {
                        if (selected != "yes") {
                            return;
                        }
                        var rec = documentListGrid.store.getById(selectedRow.id);
                        documentListGrid.store.remove(rec);
                    });
                }
            }
            ],
         // config options for stateful behavior
            stateful: true,
            stateId: 'documentListGrid'
        });
        var documentListEditForm = new Ext.form.FormPanel({
            baseCls: 'x-plain',
            labelWidth: 95,
            defaultType: 'textfield',
        
            items: [{
                fieldLabel: '<fmt:message key="documentList.grid.name"/>',
                name: 'name',
                allowBlank: false,
                anchor:'100%'
            }, new Ext.form.ComboBox({
                fieldLabel: '<fmt:message key="documentList.grid.project"/>',
                hiddenName:'projectId',
                store: projectListDataStore,
                forceSelection: true,
                valueField:'id',
                displayField:'name',
                typeAhead: true,
                mode: 'local',
                triggerAction: 'all',
                selectOnFocus:true,
                anchor: '100%'
            }), new Ext.form.ComboBox({
                fieldLabel: '<fmt:message key="documentList.grid.assignedTo"/>',
                hiddenName:'assignedToId',
                store: userListDataStore,
                forceSelection: true,
                valueField:'id',
                displayField:'fullname',
                typeAhead: true,
                mode: 'local',
                triggerAction: 'all',
                selectOnFocus:true,
                anchor: '100%'
            })
            ]
        });

        var documentListEditWindow = new Ext.Window({
            title: '<fmt:message key="label.documentList.editform"/>',
            width: 500,
            height:300,
            minWidth: 300,
            minHeight: 200,
            layout: 'fit',
            plain:true,
            bodyStyle:'padding:5px;',
            buttonAlign:'center',
            closeAction: 'hide',
            items: documentListEditForm,
            
            createOnSave: true,
            recordToEdit: undefined,
            buttons: [{
                text: '<fmt:message key="label.save"/>',
                handler: function() {
                    if (!documentListEditForm.getForm().isValid()) {
                        return;
                    }
                    var p = new documentListGrid.store.recordType(documentListEditForm.getForm().getValues());
                    if (documentListEditWindow.createOnSave) {
                        documentListDataStore.addSorted(p);
                    } else {
                        documentListEditForm.getForm().updateRecord(documentListEditWindow.recordToEdit);
                    }
                    documentListGrid.stopEditing();
                    documentListEditForm.getForm().reset()
                    documentListEditWindow.hide();
                }
            },{
                text: '<fmt:message key="label.cancel"/>',
                handler: function() {
                    documentListEditForm.getForm().reset()
                    documentListEditWindow.hide();
                }
            }]
        });

        var projectDataStore = new Ext.data.GroupingStore({
            id: 'project',
            pruneModifiedRecords: true,
            proxy: Ext.data.JsonHttpProxy({
                api: {
                    read :    '/project/read.action',
                    create :  '/project/create.action',  // Server MUST return idProperty of new record
                    update :  '/project/update.action',
                    destroy : '/project/destroy.action'
                }
            }),
            reader: new Ext.data.JsonReader({
                root: 'rows',
                fields: [
                         { name: 'id' },
                         { name: 'name' },
                         { name: 'assignedToId' },
                         { name: 'assignedTo' },
                         { name: 'modified' }
                ]
            }),
            writer: new Ext.data.JsonWriter({
                encode: false,
                writeAllFields: true
            })
        });

        var projectGrid = new Ext.grid.GridPanel({
            iconCls: 'icon-grid',
            frame: true,
            title: '<fmt:message key="title.projects"/>',
            store: projectDataStore,
            columns: [
                {id:'id',header: '<fmt:message key="project.grid.name"/>', width: 150, sortable: true, dataIndex: 'name'},
                {header: '<fmt:message key="project.grid.assignedTo"/>', width: 150, sortable: true, dataIndex: 'assignedTo'},
                {header: '<fmt:message key="project.grid.modified"/>', width: 140, sortable: true, dataIndex: 'modified'}
            ],
            view: new Ext.grid.GroupingView({
                forceFit:true
            }),
            tbar: [{
                text: '<fmt:message key="project.add"/>',
                iconCls: 'silk-add',
                handler : function(){
                    projectEditForm.getForm().reset();
                    userListDataStore.load();
                    projectEditWindow.createOnSave = true;
                    projectEditWindow.show();
                }
            }, {
                text: '<fmt:message key="project.edit"/>',
                handler : function(){
                    var selectedRow = projectGrid.getSelectionModel().getSelected();
                    if (!selectedRow) {
                        Ext.MessageBox.alert('<fmt:message key="label.attention"/>', '<fmt:message key="label.nothingselected"/>');
                        return false;
                    }
                    var rec = projectGrid.store.getById(selectedRow.id);
                    projectEditForm.getForm().loadRecord(rec);
                    projectEditWindow.createOnSave = false;
                    projectEditWindow.recordToEdit = rec;
                    projectEditWindow.show();
                    projectGrid.stopEditing();
                }
            }, {
                text: '<fmt:message key="project.delete"/>',
                iconCls: 'silk-delete',
                handler : function() {
                    var selectedRow = projectGrid.getSelectionModel().getSelected();
                    if (!selectedRow) {
                        Ext.MessageBox.alert('<fmt:message key="label.attention"/>', '<fmt:message key="label.nothingselected"/>');
                        return false;
                    }
                    Ext.MessageBox.confirm('<fmt:message key="label.confirm"/>', '<fmt:message key="label.areyousure"/>', function(selected) {
                        if (selected != "yes") {
                            return;
                        }
                        var rec = projectGrid.store.getById(selectedRow.id);
                        projectGrid.store.remove(rec);
                    });
                }
            }
            ],
         // config options for stateful behavior
            stateful: true,
            stateId: 'projectGrid'
        });
        var projectEditForm = new Ext.form.FormPanel({
            baseCls: 'x-plain',
            labelWidth: 95,
            defaultType: 'textfield',
        
            items: [{
                fieldLabel: '<fmt:message key="project.grid.name"/>',
                name: 'name',
                allowBlank: false,
                anchor:'100%'
            }, new Ext.form.ComboBox({
                fieldLabel: '<fmt:message key="project.grid.assignedTo"/>',
                hiddenName:'assignedToId',
                store: userListDataStore,
                forceSelection: true,
                valueField:'id',
                displayField:'fullname',
                typeAhead: true,
                mode: 'local',
                triggerAction: 'all',
                selectOnFocus:true,
                anchor: '100%'
            })
            ]
        });

        var projectEditWindow = new Ext.Window({
            title: '<fmt:message key="label.project.editform"/>',
            width: 500,
            height:300,
            minWidth: 300,
            minHeight: 200,
            layout: 'fit',
            plain:true,
            bodyStyle:'padding:5px;',
            buttonAlign:'center',
            closeAction: 'hide',
            items: projectEditForm,
            
            createOnSave: true,
            recordToEdit: undefined,
            buttons: [{
                text: '<fmt:message key="label.save"/>',
                handler: function() {
                    if (!projectEditForm.getForm().isValid()) {
                        return;
                    }
                    var p = new projectGrid.store.recordType(projectEditForm.getForm().getValues());
                    if (projectEditWindow.createOnSave) {
                        projectDataStore.addSorted(p);
                    } else {
                        projectEditForm.getForm().updateRecord(projectEditWindow.recordToEdit);
                    }
                    projectGrid.stopEditing();
                    projectEditForm.getForm().reset()
                    projectEditWindow.hide();
                }
            },{
                text: '<fmt:message key="label.cancel"/>',
                handler: function() {
                    projectEditForm.getForm().reset()
                    projectEditWindow.hide();
                }
            }]
        });
</c:if>
<c:if test="${adminMode}">
        var userDataStore = new Ext.data.GroupingStore({
            id: 'user',
            pruneModifiedRecords: true,
            proxy: Ext.data.JsonHttpProxy({
                api: {
                    read :    '/user/read.action',
                    create :  '/user/create.action',  // Server MUST return idProperty of new record
                    update :  '/user/update.action',
                    destroy : '/user/destroy.action'
                }
            }),
            reader: new Ext.data.JsonReader({
                root: 'rows',
                fields: [
                         { name: 'id' },
                         { name: 'login' },
                         { name: 'password' },
                         { name: 'fullname' },
                         { name: 'manager' }
                ]
            }),
            writer: new Ext.data.JsonWriter({
                encode: false,
                writeAllFields: true
            })
        });

        var userGrid = new Ext.grid.GridPanel({
            iconCls: 'icon-grid',
            frame: true,
            title: '<fmt:message key="title.users"/>',
            store: userDataStore,
            columns: [
                {id:'id',header: '<fmt:message key="user.grid.login"/>', width: 150, sortable: true, dataIndex: 'login'},
                {header: '<fmt:message key="user.grid.fullname"/>', width: 150, sortable: true, dataIndex: 'fullname'},
                {header: '<fmt:message key="user.grid.manager"/>', width: 140, sortable: true, dataIndex: 'manager', renderer: yesnoRenderer}
            ],
            view: new Ext.grid.GroupingView({
                forceFit:true
            }),
            tbar: [{
                text: '<fmt:message key="user.add"/>',
                iconCls: 'silk-add',
                handler : function(){
                    userEditForm.getForm().reset();
                    userEditWindow.createOnSave = true;
                    userEditWindow.show();
                }
            }, {
                text: '<fmt:message key="user.edit"/>',
                handler : function(){
                    var selectedRow = userGrid.getSelectionModel().getSelected();
                    if (!selectedRow) {
                        Ext.MessageBox.alert('<fmt:message key="label.attention"/>', '<fmt:message key="label.nothingselected"/>');
                        return false;
                    }
                    var rec = userGrid.store.getById(selectedRow.id);
                    userEditForm.getForm().loadRecord(rec);
                    userEditWindow.createOnSave = false;
                    userEditWindow.recordToEdit = rec;
                    userEditWindow.show();
                    userGrid.stopEditing();
                }
            }, {
                text: '<fmt:message key="user.delete"/>',
                iconCls: 'silk-delete',
                handler : function() {
                    var selectedRow = userGrid.getSelectionModel().getSelected();
                    if (!selectedRow) {
                        Ext.MessageBox.alert('<fmt:message key="label.attention"/>', '<fmt:message key="label.nothingselected"/>');
                        return false;
                    }
                    Ext.MessageBox.confirm('<fmt:message key="label.confirm"/>', '<fmt:message key="label.areyousure"/>', function(selected) {
                        if (selected != "yes") {
                            return;
                        }
                        var rec = userGrid.store.getById(selectedRow.id);
                        userGrid.store.remove(rec);
                    });
                }
            }
            ],
         // config options for stateful behavior
            stateful: true,
            stateId: 'userGrid'
        });

        var userEditForm = new Ext.form.FormPanel({
            baseCls: 'x-plain',
            labelWidth: 95,
            defaultType: 'textfield',
        
            items: [{
                fieldLabel: '<fmt:message key="user.grid.login"/>',
                name: 'login',
                allowBlank: false,
                anchor:'100%'
            },{
                fieldLabel: '<fmt:message key="user.grid.fullname"/>',
                name: 'fullname',
                allowBlank: false,
                anchor: '100%'
            },{
                fieldLabel: '<fmt:message key="user.grid.password"/>',
                name: 'password',
                allowBlank: false,
                inputType:'password',
                anchor: '100%'
            }, new Ext.form.ComboBox({
                fieldLabel: '<fmt:message key="user.grid.manager"/>',
                hiddenName:'manager',
                store: new Ext.data.ArrayStore({
                    fields: ['value', 'display'],
                    data : [
                        ['true', '<fmt:message key="label.yes"/>'],
                        ['false', '<fmt:message key="label.no"/>']
                    ]
                }),
                forceSelection: true,
                valueField:'value',
                displayField:'display',
                typeAhead: true,
                mode: 'local',
                triggerAction: 'all',
                selectOnFocus:true,
                anchor: '100%'
            })
            ]
        });

        var userEditWindow = new Ext.Window({
            title: '<fmt:message key="label.user.editform"/>',
            width: 500,
            height:300,
            minWidth: 300,
            minHeight: 200,
            layout: 'fit',
            plain:true,
            bodyStyle:'padding:5px;',
            buttonAlign:'center',
            closeAction: 'hide',
            items: userEditForm,
            
            createOnSave: true,
            recordToEdit: undefined,
            buttons: [{
                text: '<fmt:message key="label.save"/>',
                handler: function() {
                    if (!userEditForm.getForm().isValid()) {
                        return;
                    }
                    var p = new userGrid.store.recordType(userEditForm.getForm().getValues());
                    if (userEditWindow.createOnSave) {
                        userDataStore.addSorted(p);
                    } else {
                        userEditForm.getForm().updateRecord(userEditWindow.recordToEdit);
                    }
                    userGrid.stopEditing();
                    userEditForm.getForm().reset()
                    userEditWindow.hide();
                }
            },{
                text: '<fmt:message key="label.cancel"/>',
                handler: function() {
                    userEditForm.getForm().reset()
                    userEditWindow.hide();
                }
            }]
        });

</c:if>
        var viewport = new Ext.Viewport({
            layout: 'border',
            items: [
            // create instance immediately
            new Ext.BoxComponent({
                region: 'north',
                height: 32, // give north and south regions a height
                autoEl: {
                    tag: 'div',
                    html:'<p align="right"><fmt:message key="label.logged.as"/> ${user.fullname} <a href="/login.page"><fmt:message key="menu.logout"/></a></p>'
                }
            }), {
                // lazily created panel (xtype:'panel' is default)
                region: 'south',
                contentEl: 'footer',
                split: true,
                height: 50,
                minSize: 100,
                maxSize: 200,
                collapsible: true,
                title: '',
                margins: '0 0 0 0'
            },
            new Ext.TabPanel({
                region: 'center', // a center region is ALWAYS required for border layout
                deferredRender: false,
                activeTab: 0,
                items: [{
                    contentEl: 'main',
                    title: '<fmt:message key="menu.header.main"/>',
                    layout: 'border',
                    defaults: {
                        collapsible: true,
                        split: true
                    },
                    closable: false,
                    autoScroll: true,
                    items: [{
                        region:'west',
                        split:true,
                        width: 300,
                        bodyStyle: 'padding:0px',
                        layout:'accordion',
                        items:[{
                            title: '',
                            items: [documentGrid]
                        }]
            
                    },{
                        collapsible: false,
                        region:'center',
                        items: [new Ext.TabPanel({
                            activeTab: 0,
                            defaults: {
                                autoHeight: true
                            },
                            items: [{
                                title: '<fmt:message key="menu.header.editor"/>',
                                closable: false,
                                autoScroll: true,
                                html: '<form id="documentTextForm" onsubmit="return false;"><input id="documentId" name="documentId" type="hidden" value="0"/><textarea id="text" name="text" style="width:400px; height:300px" cols="80" rows="20"></textarea></form>'
                                
                            }, {
                                title: '<fmt:message key="menu.header.history"/>',
                                closable: false,
                                autoScroll: true,
                                items: [documentHistoryGrid]
                            }]
                        })]
                    }]
                }
<c:if test="${managerMode}">
                , {
                    contentEl: 'projects',
                    title: '<fmt:message key="menu.header.projects"/>',
                    autoScroll: true,
                    items: [projectGrid, documentListGrid]
                }
</c:if>
<c:if test="${adminMode}">
               , {
                   contentEl: 'admin',
                   title: '<fmt:message key="menu.header.admin"/>',
                   autoScroll: true,
                   items: [userGrid]
               }
</c:if>
               ]
            })]
        });

        var documentEditor = CKEDITOR.replace( 'text', {
                skin : 'office2003',
                toolbar :
                    [
                        ['Save','NewPage','Preview','-','Templates'],
                        ['Cut','Copy','Paste','PasteText','PasteFromWord','-','Print', 'SpellChecker', 'Scayt'],
                        ['Undo','Redo','-','Find','Replace','-','SelectAll','RemoveFormat'],
                        ['Bold','Italic','Underline','Strike','-','Subscript','Superscript'],
                        '/',
                        ['NumberedList','BulletedList','-','Outdent','Indent','Blockquote'],
                        ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],
                        ['BidiLtr', 'BidiRtl'],
                        ['Link','Unlink','Anchor'],
                        ['Image','Table','HorizontalRule','Smiley','SpecialChar','PageBreak'],
                        '/',
                        ['Styles','Format','Font','FontSize'],
                        ['TextColor','BGColor'],
                        ['Maximize']
                    ]
        });

        documentEditor.on( 'beforeCommandExec', function( e, data ){
            if (e.data.name == 'save') {
                documentContext.documentSaveText();
                e.cancel();
            }
        });

        var documentContext = new ru.minidoc.Context({
            viewport: viewport,
            editor: documentEditor,
            historyDataStore: documentHistoryDataStore
        });

<c:if test="${adminMode}">
        userDataStore.load();
</c:if>
<c:if test="${managerMode}">
        projectDataStore.load();
        documentListDataStore.load();
</c:if>
        documentDataStore.load();
        //hide loading
        var hideMask = function () {
            Ext.get('loading').remove();
            Ext.fly('loading-mask').fadeOut({
                remove:true
            });
        };

        hideMask.defer(250);
    });

    </script>
    <div id="main" class="x-hide-display">
    </div>

    <div id="projects" class="x-hide-display">
    </div>
<c:if test="${adminMode}">
    <div id="admin" class="x-hide-display">
        <div id="user-grid"></div>
    </div>
</c:if>
    <div id="footer" class="x-hide-display">
         <p align="right">(c) 2011</p>
    </div>
    </body>
</html>
